/**
 * TencentCloudChat 通讯核心
 * TIMUploadPlugin 文件上传到腾讯云对象存储
 * TIMProfanityFilterPlugin 敏感词审核插件
 */
import {Session, Local} from '@/utils/storage';
import TencentCloudChat from '@tencentcloud/chat';
import TIMUploadPlugin from 'tim-upload-plugin';
import bus from 'vue3-eventbus'
import {ElMessage} from "element-plus";

//创建实例
function create(listening: boolean = true) {
  let chat = undefined
  // SDKAppID 新加坡教育
  let options = {SDKAppID: null,};
  // 创建 SDK 实例，`TIM.create()`方法对于同一个 `SDKAppID` 只会返回同一份实例
  chat = TencentCloudChat.create(options);
  console.log(TencentCloudChat)
  // 接入日志，等级为2
  chat.setLogLevel(2);
  // 注册腾讯云即时通信 IM 上传插件
  chat.registerPlugin({'tim-upload-plugin': TIMUploadPlugin});
  // 注册腾讯云即时通信 IM 本地审核插件
  // chat.registerPlugin({'tim-profanity-filter-plugin': TIMProfanityFilterPlugin});
  console.log('======================================TIM实例创建成功===================================')
  //默认主动开启监听
  if (listening) {
    messageListening(chat)
  } else {
    messageListening(chat, false)
  }
  return chat
}

const chatLogin = (chat: any, status: boolean = true) => {
  if (Object.keys(Local.get('ZJ_userInfo')).length > 0 && status) {
    return new Promise((resolve, reject) => {
      chat.login({
        userID: Local.get('ZJ_userInfo').userInfo.userId,
        userSig: Local.get('ZJ_userInfo').userSig
      }).then((res: any) => {
        console.log('已登录')
        console.log(res)
        resolve(res)
      }).catch((err: any) => {
        reject(err)
        console.log('登录失败')
        console.log(err)
      })
    })
  } else {
    chat.logout();
    messageListening(chat, false)
    console.log('已登出')
  }


}

//监听控制函数
function messageListening(chat: any, status: boolean = true) {
  console.log(chat)
  if (status) {
    newMessageAlert(chat)
  } else {
    chat.off(TencentCloudChat.EVENT.SDK_READY);
    chat.off(TencentCloudChat.EVENT.SDK_NOT_READY);
  }
}

/**
 * 监听函数
 * @param chat 实例
 */
function newMessageAlert(chat: any) {

  console.log(chat)
  chat.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, (event: any) => {
    //消息提示音
    if (event.data[0].payload.description !== 'command' && event.data[0].payload.description !== 'TRTC') {
      // const innerAudioContext = uni.createInnerAudioContext();
      // innerAudioContext.src = 'https://dushuba.oss-cn-guangzhou.aliyuncs.com/sounding/xiaoxi.mp3'
      // innerAudioContext.play()
    }
    //uniApp方法
    // uni.$emit('sessionInit')
    bus.emit('sessionInit')
    console.log('收到一条新消息', event);
    // uni.$TIM.formatMessage(event.data);
    bus.emit("MESSAGE_RECEIVED", event);
    console.log('已发送')
  })
  //TIM Ready 事件
  chat.on(TencentCloudChat.EVENT.SDK_READY, (event: any) => {
    // store.commit('$setStore', {
    //   name: 'vTIM.isReady',
    //   value: true
    // });
    chat.TIM = {
      EVENT: TencentCloudChat.EVENT,
      TSignaling: TencentCloudChat.TSignaling,
      TYPES: TencentCloudChat.TYPES,
    }
    console.log('=====================================监听开启===================================')
  });
  chat.on(TencentCloudChat.EVENT.SDK_NOT_READY, (event: any) => {
    // store.commit('$setStore', {
    //   name: 'vTIM.isReady',
    //   value: false
    // });
  })
}

/**
 * 对外开放函数
 * @param chat 实例
 */
function message(chat: any) {
  // console.log(chat)
  if (chat) {
    /**
     * 获取全量的会话列表
     */
    function getConversationList() {
      return chat.getConversationList();
    }

    /**
     * 获取群聊列表
     */
    function getGroupList() {
      return chat.getGroupList();
    }

    /**
     * 获取群聊详情信息
     */
    function getGroupInfo(data: object) {
      if (Object.keys(data).length > 0) {
        return chat.getGroupProfile(data)
      }
    }

    /**
     * 获取群成员列表
     */
    function getGroupMemberList(data: object) {
      if (Object.keys(data).length > 0) {
        return chat.getGroupMemberList(data)
      }
    }

    /**
     * 获取消息列表
     * @param data
     * @param data.conversationID C2C${userID}（单聊） GROUP${groupID}（群聊） GROUP${topicID}（话题）@TIM#SYSTEM（系统通知会话）
     * @param data.nextReqMessageID
     */
    function getMessageList(data: object) {
      if (Object.keys(data).length > 0) {
        return chat.getMessageList(data);
      } else {
        console.error('请传入参数=>getMessageList')
      }
    }

    /**
     * 获取会话资料
     * @param data
     * @param data.conversationID C2C${userID}（单聊） GROUP{groupID}（群聊）@TIM#SYSTEM（系统通知会话）
     */
    function getConversationProfile(data: object) {
      if (Object.keys(data).length > 0) {
        return chat.getConversationProfile(data);
      } else {
        console.error('请传入参数=>getMessageList')
      }
    }

    /**
     * 获取会话未读总数
     */
    function getTotalUnreadMessageCount() {
      return chat.getTotalUnreadMessageCount();
    }

    /**
     * 发送消息回调
     */
    function sendMessage(message: any) {
      return chat.sendMessage(message)
    }

    /**
     * 创建文本消息
     * @param data
     * @param type C2C CONV_GROUP
     */
    function createTextMessage(data: object, type: string) {
      console.log(data,type)
      let message = chat.createTextMessage({
        to: data.id,
        conversationType: type === 'C2C' ? TencentCloudChat.TYPES.CONV_C2C : TencentCloudChat.TYPES.CONV_GROUP,
        payload: {
          text: data.text
        },
      });
      return sendMessage(message)
    }

    /**
     * 创建图片消息
     * file 用于选择图片的 DOM 节点（Web）或者 File 对象（Web）或者微信小程序 wx.chooseMedia
     *    接口的 success 回调参数，或 uni.chooseMedia 接口的 success 回调参数。SDK 会读取其
     *    中的数据并上传图片
     * @param data
     * @param type C2C CONV_GROUP
     */
    function createImageMessage(data: object, type: string) {
      let message = chat.createImageMessage({
        to: data.id,
        conversationType: type === 'C2C' ? TencentCloudChat.TYPES.CONV_C2C : TencentCloudChat.TYPES.CONV_GROUP,
        payload: {
          file: data.file
        },
      });
      return sendMessage(message)
    }

    /**
     * 创建文件消息
     * @param data
     * @param type
     */
    function createFileMessage(data: object, type: string) {
      let message = chat.createFileMessage({
        to: data.id,
        conversationType: type === 'C2C' ? TencentCloudChat.TYPES.CONV_C2C : TencentCloudChat.TYPES.CONV_GROUP,
        payload: {
          file: data.file
        },
      });
      return sendMessage(message)
    }

    return {
      getConversationList,
      getGroupInfo,
      getGroupList,
      getMessageList,
      getConversationProfile,
      getTotalUnreadMessageCount,
      createTextMessage,
      createImageMessage,
      createFileMessage,
      getGroupMemberList
    }
  } else {
    console.error('请先注入创建好的实例=>message')
    create({})
  }
}

export default {
  create,
  chatLogin,
  message
}